package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.ClientDAOImpl;
import edu.cmu.cs.webapp.ioms.dao.impl.FormulaDAOImpl;
import edu.cmu.cs.webapp.ioms.dao.impl.ProductDAOImpl;
import edu.cmu.cs.webapp.ioms.models.FormularRecord;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.models.PurchaseOrder;
import edu.cmu.cs.webapp.ioms.models.impl.ProductImpl;
import edu.cmu.cs.webapp.ioms.ui.wizards.formula.FormularWizard;
import edu.cmu.cs.webapp.ioms.ui.wizards.product.ProductWizard;
import edu.cmu.cs.webapp.ioms.views.IngredientListView;
import edu.cmu.cs.webapp.ioms.views.ProductView;

public class EditFormulaViewAction implements IViewActionDelegate {

	private FormularRecord model;
	private IngredientListView _view;
	private Product _product;

	@Override
	public void init(IViewPart view) {
		this._view = (IngredientListView) view;

	}

	@Override
	public void run(IAction action) {
		// if (this.model != null) {
		// ProductWizard

		Object sel = ((IStructuredSelection) ProductView
				.getProductsListViewPart(this._view.getViewSite())
				.getSelection()).getFirstElement();

		if (sel != null && sel instanceof Product) {
			this._product = (Product) sel;

		}

		FormularWizard wizard = new FormularWizard(true, model);

		wizard.setWindowTitle("Edit Formula Information");
		WizardDialog dialog = new WizardDialog(_view.getViewSite().getShell(),
				wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();

		// just either ok or cancel
		int returnCode = dialog.getReturnCode();

		if (returnCode == org.eclipse.jface.window.Window.OK) {

			try {
				FormularRecord fr = wizard.getModel();
				fr.setProduct(_product);
				new FormulaDAOImpl().updateFormula(fr);
				
				this._view.refIngrListView();

			} catch (DataAccessException e) {
			}

		} else {
		}


	}

	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// for testing purpose, using the class
			if (obj instanceof FormularRecord) {
				// manually create a new product
				this.model = (FormularRecord) obj;

			}
		}
	}
}
